// miniprogram/pages/admin/index/index.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    opacity: 1,
    colors: ['#ff816d', '#ffaa4b', '#9e8eff', '#1fbfa9', '#63a9fe'],
    menu: [
      //   {
      //   title: "品牌",
      //   url: '../studio/studio',
      //   icon: 'icon-xiangjix'
      // },
      {
        title: "套系",
        url: '../service/service/service',
        icon: 'icon-taoxi'
      },
      {
        title: "作品",
        url: '../portfolio/portfolio',
        icon: 'icon-kepian'
      },
      {
        title: "个性化",
        url: '../customize/customize',
        icon: 'icon-zhuangxiu'
      },
      {
        title: "档期",
        url: '../schedule/schedule',
        icon: 'icon-rili'
      },

      // {
      //   title: "海报制作",
      //   url: '../../magic/poster/poster',
      //   icon: 'icon-haibao'
      // },

      {
        title: "客户",
        url: '../customer/customer',
        icon: 'icon-kehu'
      },
      {
        title: "同事",
        url: '../team/team',
        icon: 'icon-tongshi'
      },
      {
        title: "存储",
        url: '../cos/cos',
        icon: 'icon-rongliang'
      },
      {
        title: "消息设置",
        url: '../subscribeMsg/subscribeMsg',
        icon: 'icon-shezhi'
      },


    ],
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getSettings()
    // console.log('load')
    let scene = wx.getLaunchOptionsSync().scene
    console.log('scene', scene)
    this.setData({
      scene
    })
    const that = this;
    app.login(user => {
      console.log('user', user)
      this.setData({
        user
      });
      if (this.options.studioid && this.options.studioid != user.studioid) {
        this.switchStudio(this.options.studioid);
        return;
      }
      if (!user.studioid) {
        return;
      }
      wx.showNavigationBarLoading();
      this.getStudioList();
      this.listOrder(user.studioid);
      //隐藏导航条加载动画
      wx.hideNavigationBarLoading();
      //停止下拉刷新
      wx.stopPullDownRefresh();

    });

  },
  getUserInfo: function (e) {
    console.log(e)
    let user = this.data.user;
    if (!user) user = {};

    wx.getUserProfile({
      desc: '业务需要',
      success: res => {
        console.log(res) 
        let userinfo = res.userInfo
//
        if (!userinfo) {
          this.setData({
            modalname: 'shouquan'
          })

        } else {
          this.hideModal()
          user.nickName = userinfo.nickName;
          user.avatarUrl = userinfo.avatarUrl;
          user.country = userinfo.country;
          user.province = userinfo.province;
          user.gender = userinfo.gender;
          user.city = userinfo.city;


          if (!user._id) {
            user._id = user.openid;
            wx.cloud.callFunction({
              name: 'crud',
              data: {
                table: 'user',
                op: 'add',
                data: user,
              },
              success: res => {
                this.onLoad()

              }
            })
          } else {
            user._id = user.openid;
            wx.cloud.callFunction({
              name: 'crud',
              data: {
                table: 'user',
                op: 'update',
                data: user
              },

            })
          }
        }
      }
    })
  },
  getPhoneNumber: function (e) {
    let cloudID = e.detail.cloudID //开放数据ID
    let user = this.data.user
    if (cloudID) {
      this.hideModal()
      wx.cloud.callFunction({
        name: 'getPhone',
        data: {
          cloudID: cloudID
        }
      }).then(res => {

        user.phone = res.result.list[0].data.phoneNumber
        console.log(user.phone)
        user._id = user.openid;
        wx.cloud.callFunction({
          name: 'crud',
          data: {
            table: 'user',
            op: 'update',
            data: user
          },
          success: res => {
            console.log(res)
            wx.navigateTo({
              url: '/pages/admin/studio/studio',
            })
          }
        })
      })

    } else {
      this.setData({
        modalname: 'shouquan'
      })

    }
  },
  getStudioList: function () {
    const that = this;

    wx.cloud.callFunction({
      name: 'getMyStudioList',
      success: res => {
        if (res.result.list.length >= 1) {
          that.setData({
            studioList: res.result.list
          });
        } else {
          that.setData({
            studioList: false
          });
        }
      }
    });
  },

  getSettings() {
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'setting',
      },
      success: res => {
        app.globalData.settings = res.result.data[0]
        this.setData({
          settings: res.result.data[0]
        })
      }
    })
  },

  listOrder: function (studioid) {
    if (!studioid) return;
    const that = this;
    wx.cloud.callFunction({
      name: 'order',
      data: {
        op: 'list',
        studioid: studioid
      },
      success: res => {
        let items = [];
        res.result.list.map((v, i) => {
          items[v._id] = v.num;
        });
        that.setData({
          items: items
        });
      }
    })
  },

  navtomini(e) {
    let studioid = e.currentTarget.dataset.studioid
    console.log(studioid)
    if (!studioid) return;
    wx.navigateToMiniProgram({
      appId: app.globalData.user.studio.appid,
      extraData: {
        studioid: studioid
      },
      envVersion: "trial",
      path: `pages/user/index/index?studioid=${studioid}`,
    })
  },
  changeStudio: function (e) {
    const that = this;
    console.log(e)
    const id = e.currentTarget.dataset.id;
    if (id == that.data.studioid) return;
    that.hideModal();
    if (!id) return;
    wx.showLoading({
      title: '正在加载...',
    })
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'update',
        table: 'user',
        data: {
          _id: that.data.user.openid,
          studioid: id
        }
      },
      success: res => {
        wx.hideLoading()
        app.relogin(u => {
          that.setData({
            user: u
          });
          // that.onLoad(that.options)
          wx.showNavigationBarLoading();
          this.getStudioList();
          this.listOrder(u.studioid);
          //隐藏导航条加载动画
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
        })
      }
    })
  },

  requestSubscribeMessage(e) {
    const templateId = ['fgN7PR9idyvoDi2-l0JW-ObwnAY5cRIfz1oA002FipU', 'uzadlWcZzW4JC3rVj-vHpuVrkcR-aQ38vrpspE5gNDY', 'd2Fy2BPP1uRDHpvrsazOqDV3g4POTR9_kcOmGgYTT10']

    let that = this
    let always = true
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log(res.authSetting)
        console.log(res.subscriptionsSetting.itemSettings)
        // console.log(  )
        always = res.subscriptionsSetting.itemSettings == undefined || Object.keys(res.subscriptionsSetting.itemSettings).filter(v => {
          return templateId.includes(v)
        }).length < 1
        console.log(always)
        if (always) {
          that.setData({
            modalname: 'tip'
          })
        }
      }
    })
    wx.requestSubscribeMessage({
      tmplIds: templateId,
      success: (res2) => {
        console.log(res2)
        that.setData({
          modalname: null
        })
        wx.navigateTo({
          url: e.currentTarget.dataset.url,
        })
      },
      fail: (err) => {
        console.log('msg', `失败（${JSON.stringify(err)}）`)

      },
      complete: (res) => {

      }
    })


  },
  showModal(e) {
    let modalname = e.currentTarget.dataset.modalname

    this.setData({
      modalname
    })

  },
  hideModal() {
    this.setData({
      modalname: null
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let query = wx.createSelectorQuery();
    query.select('.studio-header').boundingClientRect(rect => {
      //获取到元素
      //  console.log(rect.height)
      this.headerHeight = rect.height
    }).exec();
    //  this.onLoad()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad()
    //  wx.reLaunch({
    //    url: '/pages/admin/index/index',
    //  })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onPageScroll: function (e) {
    // console.log(this.headerHeight)
    //console.log(e.scrollTop)
    this.setData({
      opacity: (1 - e.scrollTop / this.headerHeight).toFixed(2)
    })


    if (e.scrollTop > this.headerHeight && this.data.user.studio) {
      wx.setNavigationBarTitle({
        title: this.data.user.studio.title,
      })
    } else {
      wx.setNavigationBarTitle({
        title: '工作台',
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onShareTimeline: function () {

  }
})